<?php

include COMMON_PATH . 'Common/charset.fun.php';
include COMMON_PATH . 'Common/string.fun.php';
include COMMON_PATH . 'Common/filter.fun.php';
include COMMON_PATH . 'Common/time.fun.php';
include COMMON_PATH . 'Common/file.fun.php';
include COMMON_PATH . 'Common/helper.php';

/**
 * 将值设置到指定的KEY PATH中。
 *
 * @param string $key_path        	
 * @param mixed $value        	
 * @param string $delimiter        	
 * @return array
 */
function &setValueWithKeyPath($key_path, $value, $delimiter = '.') {
	if (! (is_string ( $key_path ) && strlen ( trim ( $key_path ) ))) {
		return NULL;
	}
	$arr = array ();
	if ((strpos ( $key_path, '.' ) === FALSE)) { // 不是KEY PATH
		$arr [$key_path] = $value;
	} else {
		$keys = (explode ( $delimiter, $key_path ));
		$i = 0;
		foreach ( array_reverse ( $keys ) as $key ) {
			if ($i ++ > 0) {
				$arr = array (
						$key => $arr 
				);
			} else {
				$arr = array (
						$key => $value 
				);
			}
		}
		unset ( $keys );
	}
	return $arr;
}

/**
 * 设置session值。当session_start未调用时，本函数会尝试调用session_start
 *
 * @param string $name        	
 * @param mixed $value        	
 */
function setSession($name, $value) {
	tryStartSession ();
        $is_key_path = (strpos ( $name, '.' ) !== FALSE);
	$keypath = array ();
	if ($is_key_path) {
		$keypath = explode ( '.', $name );
		$name = array_shift ( $keypath );
		$_SESSION [$name] = setValueWithKeyPath ( implode ( '.', $keypath ), $value );
	} else {
		$_SESSION [$name] = $value;
	}

}

/**
 * 尝试启动SESSION
 */
function tryStartSession() {
    if (! session_id () && ! headers_sent ()) {
        session_start ();
    }
}

/**
 * 获取当前SESSION ID
 *
 * @param BOOL $regenerate
 *        	是否重新生成SESSION ID
 * @return STRING
 */
function getSessionId($regenerate = FALSE) {
	tryStartSession ();
	return $regenerate ? session_regenerate_id ( TRUE ) : session_id ();
}

/**
 * 设置SESSION ID
 *
 * @param STRING $session_id        	
 * @return STRING
 */
function setSessionId($session_id) {
	tryStartSession ();
	return session_id($session_id);
}


/**
 * 判断是否是一个数组，并且是非空数组
 *
 * @param type $array        	
 * @return type
 */
function isArrayAndNotEmpty($array) {
	return (is_array ( $array ) && (! empty ( $array )));
}

/**
 * 是否是关联数组.注意，受php机制所限，如果键名是带引号的数字，也将被认为是数字索引，而不是关联数组
 * <ul>
 * <li>isAssocArray(['99'=>'a']): FALSE</li>
 * </ul>
 *
 * @param array $array        	
 * @return bool
 */
function isAssocArray(array $array) {
	return isATypeOfArray ( $array, 'is_string' );
}

/**
 * 是否是数字索引数组。注意，受php机制所限，如果键名是带引号的数字，也将被认为是数字索引。
 * <ul>
 * <li>isNumIndexArray(['99'=>'a']): TRUE</li>
 * </ul>
 *
 * @param array $array        	
 * @return bool
 */
function isNumIndexArray(array $array) {
	return isATypeOfArray ( $array, 'is_int' );
}

/**
 * 判断数组类型。
 *
 * @param array $array
 *        	要判断的数组
 * @param callback $func
 *        	回调函数
 * @return boolean
 */
function isATypeOfArray(array $array, $func) {
	if (! ($func && is_callable ( $func ))) {
		return FALSE;
	}
	
	return isArrayAndNotEmpty ( $array ) ? (array_search ( FALSE, array_map ( $func, array_keys ( $array ) ) ) === FALSE) : FALSE;
}


if ( ! function_exists('dd2char'))
{
/**
 *  生成一个随机字符
 *
 * @access    public
 * @param     string  $ddnum
 * @return    string
 */    
    function dd2char($ddnum)
    {
        $ddnum = strval($ddnum);
        $slen = strlen($ddnum);
        $okdd = '';
        $nn = '';
        for($i=0;$i<$slen;$i++)
        {
            if(isset($ddnum[$i+1]))
            {
                $n = $ddnum[$i].$ddnum[$i+1];
                if( ($n>96 && $n<123) || ($n>64 && $n<91) )
                {
                    $okdd .= chr($n);
                    $i++;
                }
                else
                {
                    $okdd .= $ddnum[$i];
                }
            }
            else
            {
                $okdd .= $ddnum[$i];
            }
        }
        return $okdd;
    }
}

/**
 * 检查是否有缩略图
 * @param type $litpic
 * @return type
 */
function isLitpic($litpic){
    if($litpic != ''){
        return $litpic;
    }
    return __ROOT__ . "/Public/default.jpg";
}




function PrintAutoFieldsAdd($field_list, $formname = 'addtable')
{
    if(is_array($field_list))
    {
        foreach($field_list as $field_info)
        {
            $yd_addonfields .= ( $yd_addonfields=="" ? $field_info['name'] . ",". $field_info['type'] : ";" . $field_info['name'] . "," . $field_info['type'] );
            echo  GetFormItem($field_info, $formname);
        }
    }
    echo "<input type='hidden' name='yd_addonfields' value=\"".$yd_addonfields."\">\r\n";
}

function PrintAutoFieldsEdit($field_list, $fieldValues, $formname = 'addtable')
{
    if(is_array($field_list))
    {
        foreach($field_list as $field_info)
        {
            $yd_addonfields .= ( $yd_addonfields=="" ? $field_info['name'] . ",". $field_info['type'] : ";" . $field_info['name'] . "," . $field_info['type'] );
            echo GetFormItemValue($field_info, $fieldValues[$field_info['name']], $formname);
        }
    }
    echo "<input type='hidden' name='yd_addonfields' value=\"".$yd_addonfields."\">\r\n";
}
/**
 * 处理HTML文本
 * 删除非站外链接、自动摘要、自动获取缩略图
 *
 * @access    public
 * @param     string  $body  内容
 * @param     string  $description  描述
 * @param     string  $dtype  类型
 * @return    string
 */
function AnalyseHtmlBody($body, &$description, $dtype='')
{
    $body = stripslashes($body);


    //删除非站内链接
    if(C("DELLINK")==1)
    {
        $allow_urls = array($_SERVER['HTTP_HOST']);
        // 读取允许的超链接设置
        if(file_exists(YDCMS_DATA."admin/allowurl.txt"))
        {
            $allow_urls = array_merge($allow_urls, file(YDCMS_DATA."admin/allowurl.txt"));
        }
        $body = Replace_Links($body, $allow_urls);
    }

    //自动摘要
    if($description=='' && C("CFG_AUOT_DESCRIPTION")>0)
    {
        $description = cn_substr(html2text($body), C("CFG_AUOT_DESCRIPTION"));
        $description = trim(preg_replace('/#p#|#e#/','',$description));
        $description = addslashes($description);
    }
    

    $body = GetFieldValueA($body,$dtype);
    $body = addslashes($body);
    return $body;
}

/**
 *  删除非站内链接
 *
 * @access    public
 * @param     string  $body  内容
 * @param     array  $allow_urls  允许的超链接
 * @return    string
 */
function Replace_Links( &$body, $allow_urls=array()  )
{
    $host_rule = join('|', $allow_urls);
    $host_rule = preg_replace("#[\n\r]#", '', $host_rule);
    $host_rule = str_replace('.', "\\.", $host_rule);
    $host_rule = str_replace('/', "\\/", $host_rule);
    $arr = '';
    preg_match_all("#<a([^>]*)>(.*)<\/a>#iU", $body, $arr);
    if( is_array($arr[0]) )
    {
        $rparr = array();
        $tgarr = array();
        foreach($arr[0] as $i=>$v)
        {
            if( $host_rule != '' && preg_match('#'.$host_rule.'#i', $arr[1][$i]) )
            {
                continue;
            } else {
                $rparr[] = $v;
                $tgarr[] = $arr[2][$i];
            }
        }
        if( !empty($rparr) )
        {
            $body = str_replace($rparr, $tgarr, $body);
        }
    }
    $arr = $rparr = $tgarr = '';
    return $body;
}

/**
 * 获得一个附加表单
 *
 * @access    public
 * @param     array  $field_info
 * @return    string
 */
function GetFormItem($field_info, $formname, $admintype='admin', $formitem = ''){
    $fieldname = $field_info['name'];
    if($formitem == ""){
        $formitem = " <tr><th width=100>~name~</th><td>~form~</td></tr><tr>\r\n";
    }
    if($field_info['type'] == 'select'){
        $myformItem = '';
        $items = explode(',', $field_info['value']);
        $myformItem = genSelect($fieldname, $items, 0, '', $formname);
        $formitem = str_replace("~name~", $field_info['comment'], $formitem);
        $formitem = str_replace("~form~", $myformItem,$formitem);
        return $formitem;
    }
    else if($field_info['type'] == 'radio')
    {
        $myformItem = '';
        $items = explode(',', $field_info['value']);
        $myformItem = genRadios($fieldname, $items, '', '', $formname);
        $formitem = str_replace("~name~", $field_info['comment'], $formitem);
        $formitem = str_replace("~form~", $myformItem,$formitem);
        return $formitem;
    }else if($field_info['type'] == 'checkbox'){
        $myformItem = '';
        $items = explode(',', $field_info['value']);
        
        $myformItem = genCheckboxs($fieldname, $items, '', '', $formname);
        $formitem = str_replace("~name~", $field_info['comment'], $formitem);
        $formitem = str_replace("~form~", $myformItem, $formitem);
        return $formitem;
    }
    
    if($field_info['type']=="htmltext"){
        $formitem = "<tr><td colspan=\"2\"><div class=\"Item hr\">
        <div class=\"current\">~name~</div>
    </div>
    <table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"table1\">
    	<tr><td>~form~</td></tr>
    </table></td></tr>";
        
        if($admintype=='admin'){
            $innertext = genEditor($fieldname, '', 120, 20, '1', $formname);
        }else if($admintype=='diy'){
            $innertext = genEditor($fieldname, '', 120, 20, 'simple', $formname);
        }else{
            $innertext = genEditor($fieldname, '', 120, 20, 'simple', $formname);
        }
        $formitem = str_replace("~name~", $field_info['comment'], $formitem);
        $formitem = str_replace("~form~", $innertext, $formitem);
        return $formitem;
    } else if($field_info['type']=="multitext") {
        $innertext = genTextarea($fieldname, '', 70, 5, $field_info['comment'], $formname);
        $formitem = str_replace("~name~",$field_info['comment'],$formitem);
        $formitem = str_replace("~form~",$innertext,$formitem);
        return $formitem;
    }else if($field_info['type']=="img") {
        if($admintype=='diy'){
            $innertext = genText($fieldname, 60, '', 'input', $formname);
            //$innertext = genFile($fieldname, '', $formname);
        }else{
            $innertext = genText($fieldname, 30, '', 'input', $formname) . genButton($fieldname.'_bt', '站内选择', 'btn btn-open', "SelectImage('form1.{$fieldname}');");
        }
        $formitem = str_replace("~name~",$field_info['comment'],$formitem);
        $formitem = str_replace("~form~",$innertext,$formitem);
        return $formitem;
    }else{
        if($field_info['value']!="") $dfvalue = $field_info['value'];
        else $dfvalue = "";
        
        $innertext = genText($fieldname, 30, $dfvalue, 'input', $formname);
        $formitem = str_replace("~name~",$field_info['comment'],$formitem);
        $formitem = str_replace("~form~",$innertext,$formitem);
        return $formitem;
    }
}

/**
 * 获得带值的表单(编辑时用)
 * @param string $field_info  字段信息
 * @param string $fvalue      变量值
 * @param string $formname    变量名称
 * @param string $admintype   会员类型
 * @param string $formitem    
 * @return string
 */
function GetFormItemValue($field_info, $fvalue, $formname, $admintype='admin', $formitem = ''){
    $fieldname = $field_info['name'];
    if($formitem == ""){
        $formitem = " <tr>
                      <th style=\"width:9em;\">~name~</th>
                    <td>~form~</td></tr>
            <tr>\r\n";
    }
    
    if($field_info['type'] == 'select'){
        $myformItem = '';
        $items = explode(',', $field_info['value']);
        $myformItem = genSelect($fieldname, $items, $fvalue, '', $formname);
        $formitem = str_replace("~name~", $field_info['comment'], $formitem);
        $formitem = str_replace("~form~", $myformItem,$formitem);
        return $formitem;
    }else if($field_info['type']=='radio'){
        $myformItem = '';
        $items = explode(',', $field_info['value']);
        $myformItem = genRadios($fieldname, $items, $fvalue, '', $formname);
        $formitem = str_replace("~name~", $field_info['comment'], $formitem);
        $formitem = str_replace("~form~", $myformItem,$formitem);
        return $formitem;
    }else if($field_info['type'] == 'checkbox'){
        $myformItem = '';
        $items = explode(',', $field_info['value']);
        $myformItem = genCheckboxs($fieldname, $items, $fvalue, '', $formname);
        $formitem = str_replace("~name~", $field_info['comment'], $formitem);
        $formitem = str_replace("~form~", $myformItem, $formitem);
        return $formitem;
    }


    if($field_info['type']=="htmltext"){
        $formitem = "<tr><td colspan=\"2\"><div class=\"Item hr\">
        <div class=\"current\">~name~</div>
    </div>
    <table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"table1\">
    	<tr><td>~form~</td></tr>
    </table></td></tr>";
        
        $innertext = genEditor($fieldname, $fvalue, 120, 20, '1', $formname);
        $formitem = str_replace("~name~", $field_info['comment'], $formitem);
        $formitem = str_replace("~form~", $innertext, $formitem);
        return $formitem;
    }else if($field_info['type']=="multitext"){
        $innertext = genTextarea($fieldname, $fvalue, 70, 5, $field_info['comment'], $formname);
        $formitem = str_replace("~name~",$field_info['comment'],$formitem);
        $formitem = str_replace("~form~",$innertext,$formitem);
        return $formitem;
    }else if($field_info['type']=="img"){
        if($admintype=='diy'){
            $innertext = genText($fieldname, 60, $fvalue, 'input', $formname);
            //$innertext = genFile($fieldname, '', $formname) . '<img src="'.$fvalue.'" width="100" />';
        }else{
            $innertext = genText($fieldname, 60, $fvalue, 'input', $formname) . genButton($fieldname.'_bt', '站内选择', 'btn btn-open', "SelectImage(\"form1.{$fieldname}\");");
        }
        $formitem = str_replace("~name~",$field_info['comment'],$formitem);
        $formitem = str_replace("~form~",$innertext,$formitem);
        return $formitem;
    }else{
        $innertext = genText($fieldname, 30, $fvalue, 'input', $formname);
        $formitem = str_replace("~name~",$field_info['comment'],$formitem);
        $formitem = str_replace("~form~",$innertext,$formitem);
        return $formitem;
    }
}

/**
 * 处理不同类型的数据
 * @param string $dvalue 默认值
 * @param string $dtype 默认类型
 * @param string $admintype 管理类型
 * @return int|string
 */
function GetFieldValue($dvalue, $dtype, $admintype='admin'){
    if($dtype=='int')
    {
        if($dvalue=='')
        {
            return 0;
        }
        return GetAlabNum($dvalue);
    }
    else if($dtype=='float')
    {
        if($dvalue=='')
        {
            return 0;
        }
        return GetAlabNum($dvalue);
    }
    else if($dtype=='datetime')
    {
        if($dvalue=='')
        {
            return 0;
        }
        return GetMkTime($dvalue);
    }
    else if($dtype=='checkbox')
    {
        $okvalue = '';
        if(is_array($dvalue))
        {
            $okvalue = join(',',$dvalue);
        }
        return $okvalue;
    }
    else if($dtype=="htmltext")
    {
        if($admintype=='diy')
        {
            $dvalue = HtmlReplace($dvalue,-1);
        }
        return $dvalue;
    }
    else if($dtype=="multitext")
    {
        if($admintype=='diy')
        {
            $dvalue = HtmlReplace($dvalue,0);
        }
        return $dvalue;
    }
    else if($dtype=='img' || $dtype=='imgfile')
    {
        if($admintype=='diy'){
            //待开发
            //return $iurl;
        }
        $iurl = stripslashes($dvalue);
        if(trim($iurl)=='')
        {
            return '';
        }
        $imgurl = trim(str_replace(C('CFG_BASEHOST'),"",$iurl));
        
        return addslashes($imgurl);
    }
    else
    {
        if($admintype=='diy')
        {
            $dvalue = HtmlReplace($dvalue,1);
        }
        return $dvalue;
    }
}

/**
 * 处理不同类型的数据
 * @param string $dvalue
 * @param string $dtype
 * @return string
 */
function GetFieldValueA($dvalue, $dtype){
    return GetFieldValue($dvalue, $dtype, 'admin');
}
